package org.gongliang.jsmile.authc.task.service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.gongliang.jsmile.authc.task.dao.QrtzTaskDao;
import org.gongliang.jsmile.authc.task.entity.QrtzTask;
import org.gongliang.jsmile.common.base.CRUDService;
import org.gongliang.jsmile.common.constants.KConstant;
import org.gongliang.jsmile.common.exception.JSmileException;
import org.gongliang.jsmile.common.kit.StrKit;
import org.gongliang.jsmile.common.task.TaskKit;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;

/**
* 
* @author 龚亮
* @version 1.0
* @date 2018年08月25日 05:30:27
*/
@Service
public class QrtzTaskService extends CRUDService<QrtzTaskDao, QrtzTask> {

	private static final Logger logger = LoggerFactory.getLogger(QrtzTaskService.class);
	
	@Autowired
	private QrtzTaskDao taskDao;
	
	/**
	 * D:初始化任务
	 */
	@PostConstruct
	public void init() throws Exception {
		Map<String,Object> param=Maps.newHashMap();
		param.put("taskStatus", "1");
		List<QrtzTask> jobList=taskDao.findAll(param);
		List<QrtzTask> existsJobList = TaskKit.getAllJob();
		/*
		 * 删除当前系统不存在的任务
		 */
		for (QrtzTask task : existsJobList) {
			int i = Collections.frequency(jobList, task);
			if (i < 1) {
				logger.error("当前任务数量:" + existsJobList.size() + ",当前任务:【" + task.getJobName() + "】不存在!");
				TaskKit.deleteJob(task);
			}
		}
		/*
		 * 恢复或启动任务
		 */
		for (QrtzTask task : jobList) {
			if (KConstant.TASK.STATUS_STOP.equals(task.getTaskStatus())) {
				TaskKit.pauseJob(task);
			} else {
				TaskKit.existsJobUpdateCron(task);
			}
		}

	}
	/**
	 * d：创建一个定时任务
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean saveTask(QrtzTask task) throws SchedulerException {
		task.setBeanClass(task.getBeanClass().trim());
		int i=taskDao.saveOne(task);
		if(i>0) {
			TaskKit.addJob(task, null);
		}else {
			throw new JSmileException("创建定时任务失败!");
		}
		return retBool(i);
	}

	public boolean pauseJob(QrtzTask task) throws SchedulerException {
		int i=taskDao.updateById(task);
		if(i>0) {
			TaskKit.pauseJob(task);
		}else {
			throw new JSmileException("暂停定时任务失败!");
		}
		return retBool(i);
	}

	public boolean resumeJob(QrtzTask task) throws SchedulerException {
		int i=taskDao.updateById(task);
		if(i>0) {
			TaskKit.resumeJob(task);
		}else {
			throw new JSmileException("暂停定时任务失败!");
		}
		return retBool(i);
	}

	public boolean runJob(QrtzTask task)  {
		boolean flag=true;
		try {
			TaskKit.runAJobNow(task);
		} catch (SchedulerException e) {
			e.printStackTrace();
			flag=false;
		}
		return flag;
	}

	public boolean deleteTasks(String[] ids) throws SchedulerException{
		int i=0;
		if(null!=ids&&ids.length>0) {
			for(String id: ids) {
				if(StrKit.notBlank(id)) {
					QrtzTask task=new QrtzTask();
					task.setId(Integer.parseInt(id));
					task=taskDao.findById(task);
					TaskKit.deleteJob(task);
				}
			}
		}
		i=taskDao.deleteByIds(ids);
		return retBool(i);
	}
}
